//
//  MSResetPswController.m
//  MSJD
//
//  Created by xiangbo on 2018/9/24.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSResetPswController.h"

#import "MSNewTextField.h"

#import "MSLoginDataSource.h"
#import "AppDelegate.h"

#import "NSString+Regex.h"


@interface MSResetPswController ()<UITextFieldDelegate>

@property (nonatomic, strong) UIImageView *logoIcon;
@property (nonatomic, strong) MSNewTextField *phoneTextField;
@property (nonatomic, strong) MSNewTextField *codeTextField;
@property (nonatomic, strong) MSNewTextField *pswTextField;
@property (nonatomic, strong) UIButton  *confirmButton; // 确认按钮

@property (nonatomic, assign) MSResetPswType type;
@property (nonatomic, assign) MSResetPwsFromVCType fromType;

@property (nonatomic, copy) NSDictionary *codeDic; // 验证码接口获取的字典

@end

@implementation MSResetPswController {
    NSTimer *_verifyCodeCountDownTimer; // 验证码倒计时定时器
    NSInteger _countDownTime; // 倒计时时间
}

+ (instancetype)loadResetPswControllerWithType:(MSResetPswType)type fromVC:(MSResetPwsFromVCType)fromType {
    MSResetPswController *resetPswVC = [[MSResetPswController alloc] init];
    resetPswVC.type = type;
    resetPswVC.fromType = fromType;
    return resetPswVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addsubviews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self removeCountDownTimer];
}

- (void)addsubviews{
    // LOGO
    self.logoIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]];
    [self.baseView addSubview:self.logoIcon];
    
    // 手机号码输入框
    self.phoneTextField = [MSNewTextField loadNewTextFieldWithType:MSTextTypePhone];
    self.phoneTextField.textField.delegate = self;
    [self.baseView addSubview:self.phoneTextField];
    // 验证码输入框
    self.codeTextField = [MSNewTextField loadNewTextFieldWithType:MSTextTypeCode];
    self.codeTextField.textField.delegate = self;
    _WEAKSELF
    self.codeTextField.CodeButtonClickBlock = ^(UIButton * _Nonnull codeButton) {
        [weakSelf verifyButtonClick:codeButton];
    };
    [self.baseView addSubview:self.codeTextField];
    if (self.type != MSResetPswTypeBindPhone) {
        // 密码输入框
        self.pswTextField = [MSNewTextField loadNewTextFieldWithType:MSTextTypePwd];
        self.pswTextField.textField.delegate = self;
        [self.baseView addSubview:self.pswTextField];
    }
    
    // 确认修改密码按钮
    NSString *buttonTitle = @"";
    if (self.type == MSResetPswTypeRegist) {
        buttonTitle = @"注册";
    } else if (self.type == MSResetPswTypeModify) {
        buttonTitle = @"重设密码";
    } else if (self.type == MSResetPswTypeBindPhone) {
        buttonTitle = @"绑定手机";
    }
    self.confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.confirmButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.confirmButton.backgroundColor = MSThemeColor;
    [self.confirmButton setTitle:buttonTitle forState:UIControlStateNormal];
    [self.confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.confirmButton addTarget:self action:@selector(resetPwdButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.confirmButton.layer.cornerRadius = 25.0;
    [self.baseView addSubview:self.confirmButton];
    
    [self addContraints];
}

- (void)addContraints{
    CGFloat textFiledHeight = 50;
    
    CGFloat logoWidht = 72;
    CGFloat logoHeight = 72;
    [self.logoIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.baseView);
        make.top.offset(80);
        make.height.mas_equalTo(logoHeight);
        make.width.mas_equalTo(logoWidht);
    }];
    
    CGFloat buttonLeft = 25;
    [self.phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.logoIcon.mas_bottom).offset(54);
        make.left.offset(buttonLeft);
        make.right.offset(-buttonLeft);
        make.height.mas_equalTo(textFiledHeight);
    }];
    
    [self.codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneTextField.mas_bottom).offset(15);
        make.left.equalTo(self.phoneTextField.mas_left);
        make.right.equalTo(self.phoneTextField.mas_right);
        make.height.equalTo(self.phoneTextField);
    }];
    
    if (self.type != MSResetPswTypeBindPhone) {
        // 不是绑定手机界面，需要展示输入密码输入框
        [self.pswTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.codeTextField.mas_bottom).offset(15);
            make.left.equalTo(self.codeTextField.mas_left);
            make.right.equalTo(self.codeTextField.mas_right);
            make.height.equalTo(self.codeTextField);
        }];
        
        [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.pswTextField.mas_bottom).offset(40);
            make.centerX.equalTo(self.baseView);
            make.width.equalTo(self.pswTextField);
            make.height.equalTo(self.pswTextField);
        }];
    } else {

        [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.codeTextField.mas_bottom).offset(40);
            make.centerX.equalTo(self.baseView);
            make.width.equalTo(self.codeTextField);
            make.height.equalTo(self.codeTextField);
        }];
    }
    
    // baseView取整个view的尺寸
    [self.baseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.centerX.centerY.equalTo(self.view);
    }];
}

/** 初始化倒计时定时器 */
- (void)initCountDownTimer {
    [self removeCountDownTimer];
    _verifyCodeCountDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(receiveCountTimerMessage) userInfo:nil repeats:YES];
    // 修改按钮的颜色
    self.codeTextField.codeButton.hidden = YES;
    self.codeTextField.codeTimeLabel.hidden = NO;
    // 提示
    [MBProgressHUD showToastWithMessage:@"验证码已发" toView:self.view];
}
/** 移除倒计时定时器 */
- (void)removeCountDownTimer {
    if (_verifyCodeCountDownTimer) {
        if ([_verifyCodeCountDownTimer isValid]) {
            [_verifyCodeCountDownTimer invalidate];
        }
        _verifyCodeCountDownTimer = nil;
    }
}

#pragma mark - textfield delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([self.phoneTextField isEqual:textField]) {
        [self.codeTextField becomeFirstResponder];
    } else if([self.codeTextField isEqual:textField]) {
        [self.pswTextField becomeFirstResponder];
    } else if([self.pswTextField isEqual:textField]) {
        [self.pswTextField becomeFirstResponder];
    }
    return NO;
}

#pragma mark - Reset Method
/** 返回按钮点击 */
- (void)backAction {
    if (self.type == MSResetPswTypeRegist || self.type == MSResetPswTypeModify) {
         [self.navigationController popViewControllerAnimated:YES];
    } else {
        // 绑定手机
        if (self.fromType == MSResetPwsFromVCTypeSetting) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        if (self.navigationController) {
            // 切换至首页
            [self showAlertControllerWithTitle:@"未绑定手机有可能会影响一些正常的操作，您确定退出？" message:@"" confirmButton:@"继续绑定" cancelButton:@"退出" confirmClickBlock:nil cancelClickBlock:^{
                AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                [appDelegate switchRootViewController];
            }];
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = keyboardFrame.size.height;
    if ([self.phoneTextField.textField isFirstResponder]) {
        return;
    }
    // 密码输入框
    UIView *targetView = self.codeTextField;
    if (self.pswTextField) {
       targetView = [self.codeTextField.textField isFirstResponder]?self.codeTextField:self.pswTextField;
    }
    // 得到密码输入框的位置
    CGFloat maxY = CGRectGetMaxY(targetView.frame);
    if (maxY + height > MS_SCREEN_HEIGHT) {
        // 键盘和密码输入框的位置大于界面的高度，则修改baseView的中心点位置
        self.baseView.center = CGPointMake(CGRectGetWidth(self.view.frame) / 2, self.baseView.center.y - (maxY + height - MS_SCREEN_HEIGHT));
    }
}

#pragma mark - Event Response
/** 重设密码按钮点击 */
- (void)resetPwdButtonClick:(UIButton *)sender {
    if ([MSSafeObject isNull:self.phoneTextField.textField.text]) {
        [MBProgressHUD showDefaultHUDWithText:@"请输入手机号码" toView:self.view];
        return;
    }
    if ([MSSafeObject isNull:self.codeTextField.textField.text]) {
        [MBProgressHUD showDefaultHUDWithText:@"请输入验证码" toView:self.view];
        return;
    }
    if ([MSSafeObject isNull:self.pswTextField.textField.text] && self.type != MSResetPswTypeBindPhone) {
        [MBProgressHUD showDefaultHUDWithText:@"请输入密码" toView:self.view];
        return;
    }
    // 发起请求
    NSString *phone = [MSSafeObject stringInfo:self.phoneTextField.textField.text];
    NSString *code = [MSSafeObject stringInfo:self.codeTextField.textField.text];
    
    _WEAKSELF
    if (self.type == MSResetPswTypeBindPhone) {
        // 绑定手机
        [MBProgressHUD showMessage:@"绑定中..."];
        [MSLoginDataSource bindPhoneWithPhone:phone code:code codeDic:self.codeDic success:^(NSDictionary * _Nonnull responseInfo) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showDefaultHUDWithText:@"绑定成功" toView:weakSelf.view];
            [weakSelf bindPhoneSuccess:phone];
        } failure:^(NSError * _Nonnull error) {
            [MBProgressHUD hideHUD];
            NSString *errorMsg = error.localizedDescription?:@"绑定手机失败，请稍候重试";
            [MBProgressHUD showDefaultHUDWithText:errorMsg toView:weakSelf.view];
        }];
        return;
    }
    NSString *psw = [MSSafeObject stringInfo:self.pswTextField.textField.text];
    NSString *defaultErrorMsg = (self.type == 0)?@"注册账号失败，请稍候重试":@"重置密码失败，请稍候重试";
    [MBProgressHUD showMessage:(self.type == 0)?@"注册中...":@"重置密码中..."];
    [MSLoginDataSource resetPasswordWithType:self.type Phone:phone password:psw code:code codeDic:self.codeDic success:^(NSDictionary * _Nonnull responseInfo) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showDefaultHUDWithText:(self.type == 0)?@"注册成功":@"重置成功" toView:weakSelf.view];
        [weakSelf resetPswSuccess:responseInfo];
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        NSString *errorMsg = error.localizedDescription?:defaultErrorMsg;
        [MBProgressHUD showDefaultHUDWithText:errorMsg toView:weakSelf.view];
    }];
}

/** 验证码按钮点击 */
- (void)verifyButtonClick:(UIButton *)sender {
    // 判断手机号码输入框是否有值
    if ([MSSafeObject isNull:self.phoneTextField.textField.text]) {
        [MBProgressHUD showDefaultHUDWithText:@"请输入手机号" toView:self.view];
        return;
    }
    // 已有手机号
    // 验证码按钮设为不可点
    sender.enabled = NO;
    // 准备发起请求
    NSString *phone = [MSSafeObject stringInfo:self.phoneTextField.textField.text];
    _WEAKSELF
    [MSLoginDataSource sendSMSCodeWithPhone:phone source:self.type success:^(NSDictionary * _Nonnull responseInfo) {
        [weakSelf sendSMSCodeSuccess:responseInfo];
    } failure:^(NSError * _Nonnull error) {
        sender.enabled = YES;
        NSString *errorMsg = error.localizedDescription?:@"获取验证码失败";
        [MBProgressHUD showDefaultHUDWithText:errorMsg toView:weakSelf.view];
    }];
}
/** 验证码倒计时 */
- (void)receiveCountTimerMessage {
    _countDownTime--;
    if (_countDownTime > 0) {
        self.codeTextField.codeTimeLabel.text = [NSString stringWithFormat:@"%ld", _countDownTime];
    } else {
        self.codeTextField.codeButton.hidden = NO;
        self.codeTextField.codeTimeLabel.hidden = YES;
        self.codeTextField.codeTimeLabel.text = @"60";
    }
}

#pragma mark - Private Method
/** 获取验证码成功 */
- (void)sendSMSCodeSuccess:(NSDictionary *)response {
    // 开启倒计时
    self.codeDic = [MSSafeObject dictionaryInfo:response];
    _countDownTime = 60;
    [self initCountDownTimer];
}
/** 重设密码或者注册账号成功 */
- (void)resetPswSuccess:(NSDictionary *)response {
    [self.navigationController popViewControllerAnimated:YES];
}
/** 绑定手机成功 */
- (void)bindPhoneSuccess:(NSString *)phone {
    
    MSUser *loginUser = [UserAccesser loadAccount];
    loginUser.phone = phone;
    [UserAccesser saveAccountToLocal:loginUser];
    
    // 绑定手机成功跳转
    if (self.navigationController) {
        // 切换至首页
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [appDelegate switchRootViewController];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark -  Memory Method
- (void)dealloc {
    [self removeCountDownTimer];
    NSLog(@"%s", __func__);
}

@end
